<template>
    <div style="border: 1px solid #ccc">
        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef"/>
        <Editor style="height: 300px; overflow-y: hidden;" @onChange="onChange" @onCreated="handleCreated"/>
    </div>
</template>

<script setup lang="ts">
import {shallowRef, watch} from 'vue'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import {uploadApi} from '@/api'

const props = defineProps({modelValue: {type: String, default: ""}})
const emit = defineEmits(["update:modelValue"])

// 编辑器实例，必须用 shallowRef
const editorRef: any = shallowRef()
// 内容 HTML

const handleCreated = (editor: any) => {
    editorRef.value = editor // 记录 editor 实例，重要！
    //上传图片
    editor.getConfig().MENU_CONF['uploadImage'] = {
        // 自定义上传
        async customUpload(file: File, insertFn: any) {  // TS 语法
            let reader = new FileReader()
            reader.readAsDataURL(file)
            reader.onload = () => {
                uploadApi.upload.call({name: file.name, base64: reader.result}).then((res: any) => {
                    console.log(res)
                    // 自己实现上传，并得到图片 url alt href
                    insertFn(res, "", "")
                })

            }
        }
    }
    //上传视频
    editor.getConfig().MENU_CONF['uploadVideo'] = {
        // 自定义上传
        async customUpload(file: File, insertFn: any) {  // TS 语法
            // 自己实现上传，并得到视频 url poster
            // 最后插入视频
            let reader = new FileReader()
            reader.readAsDataURL(file)
            reader.onload = () => {

                uploadApi.upload.call({name: file.name, base64: reader.result}).then((res: any) => {

                    // 自己实现上传，并得到图片 url alt href
                    insertFn(res, "", "")
                })

            }
        }
    }


}

watch(() => props.modelValue, (newValue, oldValue) => {

    editorRef.value.setHtml(newValue)

})
const onChange = (editor: any) => {
    emit("update:modelValue", editor.getHtml())

}



</script>